﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum ItemType
{
    TABLE,
    DESK
}
public class GameController : MonoBehaviour
{
    public static GameController instance;
    [System.NonSerialized]
    public SystemPathFinding systemPathFinding;
    UnityEngine.Object objCustomer;
    List<GameObject> customers = new List<GameObject>();
    public Table table;
    public GameObject uiFire;

    private void Awake()
    {
        instance = this;
        objCustomer = Resources.Load("Customer");
    }
    int currentTargetX, currentTargetZ;

    public UnitNetizen netizen;

    // Start is called before the first frame update
    void Start()
    {
        systemPathFinding = gameObject.AddComponent<SystemPathFinding>();
        netizen.transform.position = FacilityController.Instance.dicPlots[10][5].transform.position;
        netizen.transform.rotation = Quaternion.Euler(new Vector3(0, -90, 0));
        currentTargetX = 10; currentTargetZ = 5;
        StartCoroutine(IEAddCustomer());
    }

    // Update is called once per frame
    void Update()
    {


    }

    public void RegisterToMain(int l, int w, int x, int y)
    {
        for (int i = x; i < x + l; i++)
        {
            for (int j = y; j < y + w; j++)
            {
                FacilityController.Instance.dicPlots[i][j].GetComponent<UnitPlot>().isOccupy = true;
                FacilityController.Instance.dicPlots[i][j].GetComponent<MeshRenderer>().material.color = Color.red;
            }
        }
    }

    public void AddNetizenTarget(Item item, int x, int z)
    {
        if (currentTargetX != x || currentTargetZ != z)
        {
            var path = systemPathFinding.FindPath(FacilityController.Instance.dicPlots[currentTargetX][currentTargetZ].GetComponent<UnitPlot>(),
                FacilityController.Instance.dicPlots[x][z].GetComponent<UnitPlot>());
            netizen.GetComponent<UnitNetizen>().paths.Enqueue(new KeyValuePair<Item, List<UnitPlot>>(item, path));
            currentTargetX = x; currentTargetZ = z;
        }
    }

    public void ResetNPCTarget()
    {
        for (int i = 0; i < customers.Count; i++)
        {
            customers[i].GetComponent<NPC>().SetTarget(i);
        }
    }

    IEnumerator IEAddCustomer()
    {
        while (true)
        {
            yield return new WaitForSeconds(UnityEngine.Random.Range(3, 6));
            if (customers.Count < 5)
            {
                var go = Instantiate(objCustomer) as GameObject;
                go.transform.position = new Vector3(-1.5f, 0, 2f);
                go.transform.rotation = Quaternion.Euler(0, 90, 0);
                customers.Add(go);
                for(int i = 0; i < customers.Count; i++)
                {
                    customers[i].GetComponent<NPC>().SetTarget(i);
                }
            }
        }
    }
}
